package cn.zn.flowTemplate.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import cn.zn.base.exception.CustomException;
import cn.zn.dept.entity.SysCorp;
import cn.zn.dept.mapper.SysCorpMapper;
import cn.zn.flowTemplate.entity.SysFlowTemplate;
import cn.zn.flowTemplate.mapper.SysFlowTemplateMapper;
import cn.zn.flowTemplate.service.SysFlowTemplateService;
import cn.zn.flowTemplate.vo.SysFlowTemplateEditVo;
import cn.zn.flowTemplate.vo.SysFlowTemplatePageVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author zn-admin
 * @since 2021-05-31
 */
@Service
public class SysFlowTemplateServiceImpl extends ServiceImpl<SysFlowTemplateMapper, SysFlowTemplate> implements SysFlowTemplateService {

    @Autowired
    private SysCorpMapper corpMapper;

    @Override
    public Object selectFlowTemplateList(SysFlowTemplatePageVo vo) {
        if (!vo.getPage()) {
            return baseMapper.selectFlowTemplateList(vo);
        }

        Page<SysFlowTemplate> page = new Page<>(vo.getCurrent(), vo.getSize());
        return baseMapper.selectFlowTemplateList(page, vo);
    }

    @Override
    @Transactional
    public void insertFlowTemplate(SysFlowTemplateEditVo vo) {
        if (checkFlowTemplateUnique(vo.getCode(), vo.getCorpId(), null)) {
            throw new CustomException("流程编号:" + vo.getCode() + "在 " + vo.getCorp() + " 中已存在，请重新编号");
        }

        SysFlowTemplate template = new SysFlowTemplate();
        BeanUtil.copyProperties(vo, template);
        template.setFlowJson(vo.getFlowNodes().toString());
        template.insert();
    }

    @Override
    @Transactional
    public void updateFlowTemplate(String id, SysFlowTemplateEditVo vo) {
        if (checkFlowTemplateUnique(vo.getCode(), vo.getCorpId(), id)) {
            throw new CustomException("流程编号:" + vo.getCode() + "在 " + vo.getCorp() + " 中已存在，请重新编号");
        }

        SysFlowTemplate template = new SysFlowTemplate();
        BeanUtil.copyProperties(vo, template);
        template.setFlowJson(vo.getFlowNodes().toString());
        template.setId(id);
        template.updateById();
    }

    /**
     * 校验流程编号是否唯一
     *
     * @param code 流程编号
     * @return 结果
     */
    private Boolean checkFlowTemplateUnique(String code, String corpId, String id) {
        QueryWrapper<SysFlowTemplate> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("CODE", code);
        queryWrapper.eq("CORP_ID", corpId);
        if (StrUtil.isNotBlank(id)) {
            queryWrapper.ne("id", id);
        }
        int count = baseMapper.selectCount(queryWrapper);
        return count > 0;
    }

    @Override
    public List<String> selectAllTables() {
        return baseMapper.selectAllTables();
    }

    @Override
    public List<JSONObject> selectAllColumnsByTable(String table) {
        return baseMapper.selectAllColumnsByTable(table);
    }

    @Override
    public SysFlowTemplate selectFlowTemplateInfo(String id) {
        SysFlowTemplate template = baseMapper.selectById(id);
        if (template != null) {
            template.setFlowNodes(JSONUtil.parseArray(template.getFlowJson()));

            SysCorp corp = corpMapper.selectById(template.getCorpId());
            List<String> corpIds = new ArrayList<>();
            if (corp != null) {
                corpIds.add(corp.getIndustryId());
            }
            corpIds.add(template.getCorpId());
            template.setCorpIds(corpIds);
        }
        return template;
    }

    @Override
    public SysFlowTemplate selectFlowTemplateInfo(String code, String corpId) {
        // 按产业查询
        if (StrUtil.isNotBlank(corpId)) {
            List<SysFlowTemplate> templates = baseMapper.selectFlowTemplateByCode(code, corpId);
            if (CollUtil.isNotEmpty(templates)) {
                return setFlowNodes(templates.get(0));
            }
        }

        // 如果产业没有，查询通用的
        List<SysFlowTemplate> templates2 = baseMapper.selectFlowTemplateByCode(code, "0");
        if (CollUtil.isNotEmpty(templates2)) {
            return setFlowNodes(templates2.get(0));
        }
        return null;
    }

    private SysFlowTemplate setFlowNodes(SysFlowTemplate template) {
        template.setFlowNodes(JSONUtil.parseArray(template.getFlowJson()));
        return template;
    }

    @Override
    @Transactional
    public void deleteFlowTemplateByIds(String[] ids) {
        baseMapper.deleteBatchIds(Arrays.asList(ids));
    }

    @Override
    @Transactional
    public void updateFlowTemplateStatus(String id, SysFlowTemplateEditVo vo) {
        SysFlowTemplate template = new SysFlowTemplate();
        template.setStatus(vo.getStatus());
        template.setId(id);
        baseMapper.updateById(template);
    }

}
